<?php

class ProductCategoriesController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/admin';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view','sub'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update','list','delete','updateStatus','upDisplay','downDisplay'),
				'users'=>array('@'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

  public function actionList($id=null)
  {
  	if($id==null) {
			$dataProvider=new CActiveDataProvider('ProductCategories',
				array (
				 'criteria' => array(
					'condition' => 'active_flag=true AND main_product_category_id is null',
					'order'=>'display_order ASC'
				 )
				)
			);
    }else {
			$dataProvider=new CActiveDataProvider('ProductCategories',
				array (
				 'criteria' => array(
				 	 'condition' => 'active_flag=true AND main_product_category_id =:main_product_category_id',
				 	 'params' => array(':main_product_category_id' => $id),
				 	 'order'=>'display_order ASC'
				 )
				)
			);    	
    }
    $this->render('list',array(
      'dataProvider'=>$dataProvider,
    ));
  }	
	
	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new ProductCategories;		
		
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['ProductCategories']))
		{
			if(empty($_POST['ProductCategories']['main_product_category_id'])) {
				unset($_POST['ProductCategories']['main_product_category_id']);	
			}
			
			$model->attributes=$_POST['ProductCategories'];
			$model->savePhoto();
			if($model->save())
				$this->redirect(array('list'));
				
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['ProductCategories']))
		{
			if(empty($_POST['ProductCategories']['main_product_category_id']) || ($model->subProductCategoriesCount > 0)) {
				$_POST['ProductCategories']['main_product_category_id']=null;	
			}
			
			if ($_POST['ProductCategories']['main_product_category_id'] != $model->main_product_category_id) {
				if (empty($model->main_product_category_id)) {
					ProductCategories::model()->updateCounters(
						array('display_order' => '-1'), 
						'main_product_category_id is null AND display_order > :display_order',
						array(':display_order' => $model->display_order)
					);
				}else {
					ProductCategories::model()->updateCounters(
						array('display_order' => '-1'), 
						'main_product_category_id = :main_product_category_id  AND display_order > :display_order',
						array('main_product_category_id' => $model->main_product_category_id, ':display_order' => $model->display_order)
					);					
				}
				
				$model->main_product_category_id = $_POST['ProductCategories']['main_product_category_id'];
				$model->display_order = $model->_nextDisplayOrder();
			}
			
			$model->attributes=$_POST['ProductCategories'];
			$model->savePhoto();
			if($model->save())
				$this->redirect(array('list','id'=>$model->main_product_category_id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
    if(Yii::app()->request->isPostRequest)
    {
      $model = $this->loadModel($id);

      ProductCategories::model()->updateCounters(
        array('display_order'=> -1),
        'display_order >:display_order',
        array(':display_order' => $model->display_order)
      );

      $model->active_flag = 0;
      $model->enable= 0;
      $model->display_order = 0;
      $model->save();

      if(!isset($_GET['ajax']))
        $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
    }
    else
      throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

  public function actionUpdateStatus($id)
  {
    $model = $this->loadModel($id);

    $model->enable = ($model->enable==true) ? 0 : 1;
    $model->save();
    $this->redirect(array('list'));

  }	

	/**
	 * Lists all models.
	 */
	public function actionIndex($data=null)
	{
		$this->layout = '//layouts/main';	
			$menusList = ProductCategories::model()->with('products','subProductCategories')->findAll(array(
      		'condition'=>'t.enable=:enable AND t.main_product_category_id is null',
      		'params'=>array(':enable' => true),
      	)); 
     if ($data == null) {
 			$modelsList = $menusList;
 			$model = new ProductCategories;
 
    }else {
    	$model =  ProductCategories::model()->find(array(
      		'condition'=>'enable=:enable AND slug=:slug',
      		'params'=>array(':enable' => true, ':slug' => $data),
      	));     	
    	
    	$modelsList = ProductCategories::model()->with('products','subProductCategories')->findAll(array(
      		'condition'=>'t.enable=:enable AND t.main_product_category_id=:main_product_category_id',
      		'params'=>array(':enable' => true, ':main_product_category_id' => $model->id),
      	));     	
    }
		$this->render('index',array(
			'modelsList'=>$modelsList,
			'menusList' => $menusList,
			'model' => $model
		));
	}

  public function actionUpDisplay($id)
  {
      $model = $this->loadModel($id);
      $display_order = $model->display_order-1;
      if (empty($model->main_product_category_id)) {
      	$prev_model = ProductCategories::model()->find(array(
      		'condition'=>'display_order=:display_order AND main_product_category_id is null',
      		'params'=>array(':display_order' => $display_order),
      	));
      }else {
      	$prev_model = ProductCategories::model()->find(array(
      		'condition'=>'display_order=:display_order AND main_product_category_id=:main_product_category_id',
      		'params'=>array(':display_order' => $display_order, ':main_product_category_id' => $model->main_product_category_id),
      	));      	
      }
      $prev_model->display_order = $prev_model->display_order+1;

      $model->display_order = $display_order;
      $prev_model->save();
      $model->save();
      $this->redirect(array('list'));
  }

  public function actionDownDisplay($id)
  {
      $model = $this->loadModel($id);
      $display_order = $model->display_order+1;

      $max_display_order = $model->getMaxDisplayOrder();
      
      if (empty($model->main_product_category_id)) {
				$next_model = ProductCategories::model()->find(array(
					'condition'=>'display_order=:display_order AND main_product_category_id is null',
					'params'=>array(':display_order' => $display_order),
				));
      }else {
				$next_model = ProductCategories::model()->find(array(
					'condition'=>'display_order=:display_order AND main_product_category_id=:main_product_category_id',
					'params'=>array(':display_order' => $display_order, ':main_product_category_id' => $model->main_product_category_id),
				));      	
      }
      if ($model->display_order < $max_display_order) {
        $next_model->display_order = $next_model->display_order-1;

        $model->display_order = $display_order;
        $next_model->save();
        $model->save();
      }
      $this->redirect(array('list'));

  }

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=ProductCategories::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='product-categories-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
